<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-form>
        <!-- 搜索栏 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              placeholder="请输入内容"
              v-model="query.query"
              class="input-with-select"
              clearable
              @clear="clear"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="search"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" @click="userAddDialog = true"
              >添加用户</el-button
            >
          </el-col>
        </el-row>
      </el-form>
      <!-- 表格 -->
      <el-table :data="users" border style="width: 100%">
        <el-table-column type="index" label="#" width="60"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="{ row }">
            <el-switch
              :disabled="row.username == 'admin'"
              v-model="row.mg_state"
              @change="changeState(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="
                handleEdit(row.id);
                userEditDialog = true;
              "
            ></el-button>
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="handleDelete(row.id)"
            ></el-button>
            <el-button
              icon="el-icon-setting"
              size="mini"
              type="warning"
              @click="assignment(row);
              distriBution = true"
             ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="userAddDialog"
      width="60%"
      :before-close="closeUserDialog"
    >
      <el-form
        :model="addform"
        :rules="addRules"
        label-width="90px"
        ref="addForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addform.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addform.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addform.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addform.mobile"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addUser">立即创建</el-button>
          <el-button @click="$refs.addForm.resetFields()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog title="修改用户" :visible.sync="userEditDialog" width="80%">
      <el-form :model="editform" label-width="90px">
        <el-form-item label="用户名">
          <el-input v-model="editform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editform.email"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="editform.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="userEditDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            userEditDialog = false;
            edit();
          "
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="distriBution"
      width="60%"
    >
      <el-form :model="assig">
        <el-form-item label="当前用户：">
          <span>{{assig.username}}</span>
        </el-form-item>
        <el-form-item label="当前角色：">
          <span>{{assig.rolename}}</span>
        </el-form-item>
        <el-form-item label="分配新角色：">
            <el-select v-model="assig.newrolename" placeholder="请选择">
              <el-option :label="item.roleName" :value="item.id" v-for="item in rolenameall" :key="item.id"></el-option>
            </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="distriBution = false">取 消</el-button>
        <el-button type="primary" @click="distriBution = false;ass(assig)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  names: "users",
  data() {
    return {
      // 分配角色对话款开关
      distriBution: false,
      assig:{
        id:'',
        username:'',
        rolename:'',
        newrolename:''
      },
      rolenameall:[],
      // 控制添加的对话框
      userAddDialog: false,
      userEditDialog: false,
      query: {
        //查询
        query: "",
        //每页几条
        pagesize: 5,
        //当前第几页
        pagenum: 1,
      },
      //总页数
      totalpages: 10,
      //总条数
      total: 0,

      //用户列表
      users: [],

      //添加表单
      addform: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 编辑菜单
      editform: {
        username: "",
        email: "",
        mobile: "",
      },
      //添加表单验证规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 分配按钮
    async assignment(row){
      const {data:{data,meta}} = await this.$http.get(`roles`)
      if(meta.status!==200) return this.$message.error("加载角色列表失败");
      this.rolenameall = data
      this.assig.id=row.id
      this.assig.username = row.username
      this.assig.rolename = row.role_name
    },
    // 确认分配
    async ass(a){
      const {data:{meta}} = await this.$http.put(`users/${a.id}/role`,{rid:a.newrolename})
      if(meta.status!==200) return this.$message.error("设置角色失败");
      this.$message.success("设置角色成功");
      this.getUsers();
    },
    //换每页几条
    handleSizeChange(val) {
      this.query.pagesize = val;
      this.getUsers();
    },
    //换页
    handleCurrentChange(val) {
      this.query.pagenum = val;
      this.getUsers();
    },
    //编辑的元数据
    async handleEdit(id) {
      const {
        data: { data, meta },
      } = await this.$http.get(`users/${id}`);
      if (meta.status == 200) {
        sessionStorage.setItem("id", id);
        this.editform.username = data.username;
        this.editform.email = data.email;
        this.editform.mobile = data.mobile;
      }
    },
    // 编辑
    async edit() {
      const id = sessionStorage.getItem("id");
      const {
        data: { data, meta },
      } = await this.$http.put(`users/${id}`, this.editform);
      if (meta.status !== 200) return this.$message.error("更新用户失败");
      this.$message.success("更新用户成功");
      sessionStorage.removeItem("id");
      this.getUsers();
    },
    //删除
    async handleDelete(id) {
      const {
        data: { data, meta },
      } = await this.$http.delete(`users/${id}`);
      if (meta.status !== 200) return this.$message.error("删除用户失败");
      this.$message.success("删除用户成功");
      this.getUsers();
    },
    async getUsers() {
      const {
        data: {
          data: { total, pagenum, users },
          meta,
        },
      } = await this.$http.get("users", {
        params: this.query,
      });
      this.users = users;
      this.query.pagenum = pagenum;
      this.total = total;
    },
    // 查询
    search() {
      this.getUsers();
    },
    clear() {
      this.getUsers();
    },
    //改变状态
    async changeState(row) {
      /*
          RESTful风格的接口请求
              GET获取数据列表操作
              POST添加数据操作
              PUT修改数据操作
              DELETE删除数据操作
          每一种操作，对应一种请求方式，就是RESTfu1风格的接口请求
      */
      console.log(row);
      const {
        data: { meta },
      } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`);
      if (meta.status !== 200) return this.$message.error("更新用户状态失败");
      this.$message.success("更新用户状态成功");
    },
    //关闭添加对话框
    closeUserDialog() {
      this.$refs.addForm.resetFields();
      this.userAddDialog = false;
    },
    //添加用户
    addUser() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const {
            data: { meta },
          } = await this.$http.post("users", this.addform);
          if (meta.status !== 201) return this.$message.error("添加用户失败");
          this.$message.success("添加用户成功");
          this.userAddDialog = false;
          this.getUsers();
        }
      });
    },
  },
  created() {
    this.getUsers();
  },
};
</script>
         